<?php
/*
 * EmailComponent for CakePHP
 *
 * @author      gwoo <gwoo@rd11.com>
 * @version     0.10.8.2176
 * @license		OPPL
 *
 */
class EmailComponent extends Object
{
	var $controller = null;
    var $to = null;
    var $from = null;
    var $subject = null;
    var $message = null;
    var $cc = null;
    var $bcc = null;
    var $charset = null;	// ISO-2022-JP or gb2312 or utf-8 or iso-8859-1
    var $content_type = null; // text/html  or  text/plain

	function startup(&$controller){
		$this->controller = $controller;
	}

    function message($thtml)
    {
    	$this->thtml = $thtml;
        ob_start();
        $this->controller->render($this->thtml);
        $this->message = ob_get_clean();
        return $this->message; 
    }

    function send()
    {
		$__lang = mb_language();
		$__enc = mb_internal_encoding();
//   		mb_language("Japanese");
   		mb_internal_encoding( mb_detect_encoding($this->subject) );
   		
		$subject = mb_encode_mimeheader($this->subject);
		$message = mb_convert_encoding($this->message, $this->charset,"AUTO");
   
   		$eol = $this->getEol();
		$headers  = 'MIME-Version: 1.0'.$eol;
		$headers .= 'Content-type: '.$this->content_type.'; charset='.$this->charset.$eol;
		$headers .= 'Content-Transfer-Encoding: 8bit'.$eol;
		$headers .= "Message-ID: <".time()." AUTO_MAILER@".$_SERVER['SERVER_NAME'].">".$eol;
		$headers .= "X-Mailer: PHP v".phpversion().$eol;	
		$headers .= "From: ".$this->from.$eol;
	  	$headers .= "Return-Path: " . $this->from.$eol;
	  	if($this->cc){
		$headers .= "CC: ".$this->cc.$eol;
	  	}
	  	if($this->bcc){
		$headers .= "BCC: ".$this->bcc.$eol;
	  	}
		
       	$success = mail($this->to, $subject, $message, $headers);

		mb_internal_encoding( $__enc );
   		mb_language($__lang); 

       	return $success;
    }

	function getEol(){
		if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN')) {
			$eol = "\r\n";
		}
		elseif (strtoupper(substr(PHP_OS, 0, 3) == 'MAC')) {
			$eol = "\r";
		} else {
			$eol = "\n";
		}
		return $eol;
	}
	
	function caculate($content,$data){
		while (list ($key, $value) = each($data)) {
			$content = str_replace("###" . $key . "###", $value, $content);
		}
		return $content;
	}
	
	function addSendJob($to,$template_id,$data){
		$templatedata = $this->controller->MaillistTemplate->find("id=$template_id");

		$subject = $templatedata['MaillistTemplate']['subject'];
		$content = $templatedata['MaillistTemplate']['template_content'];
		$subject = $this->caculate($subject,$data);
		$content = $this->caculate($content,$data);
		
		$sendjobdata = array(
						'MaillistSendJob'=>array(
											'id'=>null,
											'to'=>$to,
											'subject'=>$subject,
											'message'=>$content,
											'charset'=>$templatedata['MaillistTemplate']['charset'],
											'content_type'=>$templatedata['MaillistTemplate']['content_type'],
											'from'=>$templatedata['MaillistTemplate']['from'],
											'remain'=>'3',
											'template_id'=>$template_id
											)
							);
		$this->controller->MaillistSendJob->save($sendjobdata);
		
	}

	function encode_mimeheader($str, $mail_encoding = 'iso-2022-jp', $encoding = 'utf-8', $indent = 0)
	{
	  $start_delimiter = strtoupper("=?$mail_encoding?B?");
	  $start_pattern  = strtoupper("=\\?$mail_encoding\\?B\\?");
	  $end_delimiter  = '?=';
	
	  $str = mb_convert_encoding($str, $mail_encoding, $encoding);
	  $length  = mb_strlen($str, $mail_encoding);
	  $max_part_length = 20; // enough short in most case (you can change this default value)
	   
	  for ($i=0, $index=0; $index<$length; $i++) {
	   $part_length = $max_part_length;
	   $s = mb_substr($str, $index, $part_length, $mail_encoding);
	   // workaround for literally used start delimiter (without below, subject may break)
	   // note: mb_encode_mimeheader() don't encode ascii including start delimiter
	   if (preg_match('/^' . $start_pattern . '/i', $s))
	   {
	     $lines[$i] = $start_delimiter . base64_encode($start_delimiter) . "?=";
	     $index += strlen($start_delimiter);
	     continue;
	   }
	
	   $lines[$i] = mb_encode_mimeheader($s, $mail_encoding);
	   while (strlen($lines[$i]) > 76-1 - ($i?0:$indent)) { // max par line - first space - indent (first line only)
	     $part_length = floor($part_length * (76-1 - ($i?0:$indent)) / strlen($lines[$i])); // at least 1 decrement
	     $s = mb_substr($str, $index, $part_length, $mail_encoding);
	     $lines[$i] = mb_encode_mimeheader($s, $mail_encoding);
	   }
	   
	   // workaround for starting new line with ascii (without below, 1 space may cut in)
	   // note: mb_encode_mimeheader() starts encode after encounterring multibyte char
	   if ($i > 0 && !preg_match('/^' . $start_pattern . '/i', $lines[$i]))
	   {
	     $p = strpos($lines[$i], $start_delimiter); //never 0 (false when not found)
	     $p = $p ? $p : strlen($lines[$i]);
	     $lines[$i] = $start_delimiter . base64_encode(substr($lines[$i], 0, $p)) . "?=";
	     $part_length = $p;
	   }
	   $index += $part_length;
	  }
	  $str = join("\r\n ", $lines); // RFC 2047,822 say newline must be ^\r\n, not only\n
	  return $str;
	} 


}

?>